package com.gatewat.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;



//@Configuration
public class HostAddrKeyResolver   {


    protected static final Logger log = LoggerFactory.getLogger(HostAddrKeyResolver.class);


    //限流策略数据存储在redis中
    @Bean("redisRateLimiter")
    public RedisRateLimiter redisRateLimiter(){
        return new RedisRateLimiter(1,1);
    }

    //基于IP地址进行限流
    @Bean("remoteAddKeyResolver")
    public KeyResolver remoteAddKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
    }

    //基于hostName地址进行限流
    @Bean("remoteHostNameKeyResolver")
    public KeyResolver remoteHostNameKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostName());
    }

    //根据请求参数进行限流
    @Bean("remoteUserKeyResolver")
    public KeyResolver remoteUserKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    }


}
